package com.wuzhi.shop.product.exception;

import com.wuzhi.common.exception.BizCodeEnum;
import com.wuzhi.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理异常:
 * 1. 指定处理异常的包的位置
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.wuzhi.shop.product.controller")
//@ControllerAdvice(basePackages = "com.wuzhi.shop.product.controller")
public class WuzhishopControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();

        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

//        log.error("数据校验异常", e.getMessage(), e.getClass());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg()).put("data", errorMap);
    }

    //    其他异常
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
